﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NLBS.Entity;
using NLBS.Data;

namespace NLBS.Control
{
    public class Calendar : System.Web.UI.WebControls.Calendar
    {
        IList<Article> _monthEntries;
        // Current index into _monthEntries.
        int _currentDateIndex;
        // Number of entries in _monthEntries
        int _dateCount;
        protected override void OnLoad(EventArgs e)
        {
            this.DayRender += new DayRenderEventHandler(Calendar_DayRender);
            if (!Page.IsPostBack)
            {
                this.SelectionMode = CalendarSelectionMode.None;
                if (HttpContext.Current.Request.QueryString["date"] != null)
                {
                    DateTime date = Convert.ToDateTime(HttpContext.Current.Request.QueryString["date"]);
                    this.SelectedDate = date;
                    this.VisibleDate = date;
                }
                else
                {
                    this.SelectedDate = DateTime.Now;
                }

                this.PrevMonthText = string.Format("<a href=\"default.aspx?date={0}\">{1}</a>", this.SelectedDate.AddMonths(-1).ToString("yyyy-MM"), "&laquo;");
                this.NextMonthText = string.Format("<a href=\"default.aspx?date={0}\">{1}</a>", this.SelectedDate.AddMonths(1).ToString("yyyy-MM"), "&raquo;");
            }
            LoadMonthData();
            base.OnLoad(e);
        }

        /// <summary>
        /// Returns true if the two dates fall on the same day.
        /// </summary>
        static bool IsSameDay(DateTime date1, DateTime date2)
        {
            return (date1.Day == date2.Day) && (date1.Month == date2.Month) && (date1.Year == date2.Year);
        }

        /// <summary>
        /// Load all entries for the selected month.
        /// </summary>
        private void LoadMonthData()
        {
            _monthEntries = (List<Article>)HttpContext.Current.Cache["monthArtcileList"];

          
            if (_monthEntries == null)
            {
                _monthEntries = DbProvider.Instance().GetAllArticleByMonth(this.SelectedDate.Year, this.SelectedDate.Month);
                if (_monthEntries != null)
                {
                    HttpContext.Current.Cache.Insert("monthArtcileList", _monthEntries, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero);
                }
            }
            if (_monthEntries == null)
            {
                _dateCount = 0;
            }
            else
            {
                _dateCount = _monthEntries.Count;
            }
            _currentDateIndex = _dateCount - 1;
        }

        void Calendar_DayRender(object sender, DayRenderEventArgs e)
        {
            if (_currentDateIndex >= _dateCount || _currentDateIndex < 0)
                return;

            DateTime entryDate = _monthEntries[_currentDateIndex].PostTime;
            DateTime calDate = e.Day.Date;

            if (IsSameDay(calDate, entryDate))
            {
                e.Cell.Text = string.Format("<a class=\"calendar\" href=\"default.aspx?date={0}\">{1}</a>", e.Day.Date.ToString("yyyy-MM-dd"), e.Day.Date.Day);

                // Go through the rest of the entries. (_monthEntries should always be sorted by DateCreated in descending order)
                do
                {
                    _currentDateIndex--;
                } while (_currentDateIndex > -1 && IsSameDay(e.Day.Date, _monthEntries[_currentDateIndex].PostTime));
            }
        }
    }
}
